package app.rci.action.login;

import java.util.ArrayList;
import java.util.List;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.LocalizableError;
import app.rci.action.common.BaseActionBean;
import app.rci.domain.LoginData;
import app.rci.model.UserModel;
import app.rci.model.UserModelExample;
import app.rci.service.LoginService;

public class LoginActionBean extends BaseActionBean {
	private static final Log log        = Log.getInstance(LoginActionBean.class);
	@SpringBean LoginService loginService;
	
	private LoginData data;
	private UserModelExample userEx;
	private List<UserModel> listUser;
	
	private static final String SESSION_LOGIN= "_session_login";
	
	@DefaultHandler
	public Resolution show(){
		log.debug("++++++++++++ show ++++++++++");
		setData(null);
		return new ForwardResolution("/jsp/content/cLogin.jsp");
	}
	
	public Resolution checkLogin(){
		log.debug("+++++++++++++++ Check Login Authentication +++++++++++++++");
		
		int countRow= loginService.checkLogin(getData(), getUserEx(), getListUser());
		if(countRow > 0){
			data.setMessage("Login Berhasil");
			getContext().getRequest().getSession().setAttribute(SESSION_LOGIN, getData());
		}else{
			getContext().getValidationErrors().addGlobalError(new LocalizableError("LOGIN_NOT_SUCCESS"));
			return show();
		}
		return new ForwardResolution("/jsp/content/cMain.jsp");
	}

	public Resolution mainHome(){
		return new ForwardResolution("/jsp/content/cGridTest.jsp");
	}	
	
	public Resolution logout(){
		getContext().getRequest().getSession().invalidate();
		return show();
	}
	
	/* Setter and Getter */
	public LoginData getData() {
		if(data==null)
			data= new LoginData();		
		return data;
	}

	public void setData(LoginData data) {
		this.data = data;
	}

	public UserModelExample getUserEx() {
		if(userEx==null)
			userEx= new UserModelExample();		
		return userEx;
	}

	public void setUserEx(UserModelExample userEx) {
		this.userEx = userEx;
	}

	public List<UserModel> getListUser() {
		if(listUser==null)
			listUser= new ArrayList<UserModel>();		
		return listUser;
	}

	public void setListUser(List<UserModel> listUser) {
		this.listUser = listUser;
	}
}
